package com.vcredit.creditcat.service.loginPreview;

import com.vcredit.creditcat.util.RSAUtil;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 信而富登录预检处理类
 * Created by liaoshengjun on 2017/10/27.
 */
@Service("CRFPreviewService")
public class CRFPreviewService implements IProductPreview{
	@Value("${crf.promotion.url}")
	private String promotionUrl;

	@Value("${crf.promotion.code}")
	private String promotionCode;

	@Value("${crf.promotion.key}")
	private String promotionKey;

	private static Logger logger = LoggerFactory.getLogger(CRFPreviewService.class);

	@Override
	public Integer checkExist(String mobile) throws Exception {
		Integer result=0;
		Map<String, String> map = new HashMap<>();
		map.put("phone", mobile);// 手机号
		Map checkResult=checkCredit(map);
		if("1".equals(checkResult.get("code"))){
			result=1;
		}
		return result;
	}

	private Map checkCredit(Object parmDto) throws Exception {
		String resultJson = "";
		Map<String, String> map = (Map<String, String>) parmDto;
		try {
			String queryPar = toQueryString(map, true);
			byte[] data = queryPar.getBytes();
			byte[] encodedData = RSAUtil.encryptByPublicKey(data, promotionKey);
			String dataCrypted = new String(Base64.encodeBase64(encodedData));
			String sign = URLEncoder.encode(dataCrypted, StandardCharsets.UTF_8.name());
			map.put("systemCode", promotionCode);
			map.put("sign", sign);
			StringBuilder sb = new StringBuilder();
			sb = sb.append(promotionUrl).append("?");
			for (Map.Entry<String, String> entry : map.entrySet()) {
				sb = sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
			String url = sb.toString();
			String urlReal = url.substring(0, url.length() - 1);
			resultJson = HttpRequest.doGet(urlReal);
			logger.info("信而富登录预检接口返回："+resultJson);
			Map result = JacksonUtil.Json2Map(resultJson);
			return result;
		} catch (Exception e) {
			logger.error("信而富登录预检接口调用失败",e);
			throw e;
		}
	}

	/**
	 * 把一个map拼接成一个get请求查询传
	 *
	 *            map里面只应有业务查询参数,不应该包含sign和code
	 * @param needEncode
	 *            是否使用URLEncode编码,默认为ture
	 **/
	private String toQueryString(Map<?, ?> data, boolean needEncode) throws UnsupportedEncodingException {
		String[] keys = data.keySet().toArray(new String[data.size()]);
		Arrays.sort(keys);
		StringBuffer queryString = new StringBuffer();
		for (String key : keys) {
			queryString.append(key + "=");
			if (needEncode) {
				queryString.append(URLEncoder.encode((String) data.get(key), StandardCharsets.UTF_8.name()) + "&");
			} else {
				queryString.append(data.get(key) + "&");
			}
		}
		if (queryString.length() > 0) {
			queryString.deleteCharAt(queryString.length() - 1);
		}
		return queryString.toString();
	}
}
